Popular Searches
Popular Course Categories
Popular Courses

Conditional Rendering

Conditional Rendering

React Events and Conditional Rendering

Conditional Rendering in React JS

Conditional Rendering is an important concept in React JS that allows developers to display different UI elements or components based on specific conditions. It helps applications show the appropriate content depending on user actions, login status, permissions, data availability, loading states, and other application requirements.

Course: JustAcademy React JS Training Course

Course Demo: Register for React JS Course Demo


1. What Is Conditional Rendering?

Conditional Rendering means rendering different content based on whether a condition is true or false. React uses standard JavaScript conditions and expressions to determine what should appear in the user interface.

For example, an application can display a Welcome message when a user is logged in and a Login button when the user is logged out.

Example:

function App() {
  const isLoggedIn = true;
  return (
    <div>
      {isLoggedIn ? (
        <h2>Welcome Back!</h2>
      ) : (
        <h2>Please Log In</h2>
      )}
    </div>
  );
}
export default App;

Output: Welcome Back!

Explanation: Because isLoggedIn is true, React displays the Welcome Back message. If the value becomes false, React displays Please Log In instead.


2. Why Is Conditional Rendering Important?

Conditional Rendering helps developers build dynamic, interactive, and user-friendly applications.

  • Display different content for logged-in and logged-out users.
  • Show loading indicators while data is being fetched.
  • Display error messages when something goes wrong.
  • Show success messages after completing an action.
  • Display or hide buttons based on user permissions.
  • Show product details only when a product is selected.
  • Display validation messages when form fields are invalid.
  • Show empty-state messages when no records are available.

Common Real-World Examples

Situation Condition UI Displayed
User authentication User is logged in Dashboard or profile
Data loading Data is loading Loading message or spinner
Form validation Input is invalid Error message
Shopping cart Cart has products Cart items and total
Search results No matching results No results found message
User permissions User has permission Relevant action buttons

3. Conditional Rendering Using if Statements

The JavaScript if statement is useful when you need to choose between different outputs based on a condition. It is especially helpful when the rendering logic is more complex.

Syntax:

if (condition) {
  // Execute when the condition is true
} else {
  // Execute when the condition is false
}

Example:

function Greeting() {
  const isLoggedIn = true;
  if (isLoggedIn) {
    return <h2>Welcome User!</h2>;
  } else {
    return <h2>Please Log In</h2>;
  }
}
export default Greeting;

Explanation: The component checks the value of isLoggedIn. It returns the Welcome User heading when the value is true; otherwise, it returns the login message.

Important: JavaScript statements such as if and else cannot be written directly as statements inside JSX markup. Use them in the component's JavaScript logic before returning JSX.


4. Conditional Rendering Using if Without else

You can use an if statement to change part of the UI while keeping the rest of the component the same.

Example:

function App() {
  const isAdmin = true;
  let message = "Welcome User";
  if (isAdmin) {
    message = "Welcome Admin";
  }
  return <h2>{message}</h2>;
}
export default App;

Output: Welcome Admin

Explanation: The variable message starts with a default value. If isAdmin is true, its value changes before it is displayed.


5. Conditional Rendering Using the Ternary Operator

The ternary operator is a concise way to select one of two values or JSX elements based on a condition. It is commonly used for simple conditional rendering inside JSX.

Syntax:

condition ? expressionIfTrue : expressionIfFalse

Example:

function App() {
  const isLoggedIn = false;
  return (
    <div>
      {isLoggedIn ? (
        <h2>Welcome Back!</h2>
      ) : (
        <h2>Please Log In</h2>
      )}
    </div>
  );
}
export default App;

Output: Please Log In

Explanation: The condition is false, so React renders the second expression after the colon.

When to Use the Ternary Operator

  • When choosing between two messages.
  • When displaying Login or Logout buttons.
  • When showing Success or Error content.
  • When selecting between two UI components.

6. Conditional Rendering Using the Logical AND (&&) Operator

The logical AND operator is useful when you want to render an element only when a condition is true. If the condition is false, React generally renders no element for a boolean result.

Syntax:

{condition && expressionToRender}

Example:

function App() {
  const showMessage = true;
  return (
    <div>
      <h2>Dashboard</h2>
      {showMessage && <p>Welcome to React JS!</p>}
    </div>
  );
}
export default App;

Output: Dashboard and Welcome to React JS!

Explanation: Since showMessage is true, the paragraph is rendered. If it is false, the paragraph is omitted.

Example with a Notification

function App() {
  const unreadMessages = 3;
  return (
    <div>
      <h2>Inbox</h2>
      {unreadMessages > 0 && (
        <p>You have {unreadMessages} unread messages.</p>
      )}
    </div>
  );
}
export default App;

Output: You have 3 unread messages.

Important: Avoid using a number directly as the left-hand condition if it might be zero. For example, {'{'}unreadMessages && ...{'}'} may display 0 when the count is zero. Instead, use an explicit Boolean condition such as unreadMessages > 0.


7. Conditional Rendering Using the Logical OR (||) Operator

The logical OR operator can provide fallback content when a value is falsy. It is useful for displaying default messages when optional data is missing.

Example:

function App() {
  const userName = "";
  return (
    <div>
      <h2>Hello, {userName || "Guest"}!</h2>
    </div>
  );
}
export default App;

Output: Hello, Guest!

Explanation: Because userName is an empty string, the expression displays Guest.

Note: The || operator treats values such as an empty string, zero, false, null, and undefined as falsy. If zero is a valid value that must be displayed, choose the fallback logic carefully.


8. Conditional Rendering Using the Null Value

In React, returning null from a component means that the component renders no visible content. It can be useful when a component should not appear under a particular condition.

Example:

function Notification({ show }) {
  if (!show) {
    return null;
  }
  return <p>You have a new notification!</p>;
}
export default Notification;

Explanation: When the show prop is false, the component returns null. When it is true, the notification paragraph appears.

Using the Component:

<Notification show={true} />
<Notification show={false} />

The first component displays the notification, while the second displays nothing.


9. Conditional Rendering Using Variables

You can store JSX in a variable and then render that variable. This approach is useful when the conditional logic is more complex or when you want to keep the returned JSX easy to read.

Example:

function App() {
  const isLoggedIn = true;
  let content;
  if (isLoggedIn) {
    content = <h2>Welcome to Your Dashboard</h2>;
  } else {
    content = <h2>Please Log In</h2>;
  }
  return (
    <div>
      {content}
    </div>
  );
}
export default App;

Explanation: The variable content stores the appropriate JSX according to the condition. React then renders the value of that variable.


10. Conditional Rendering with Multiple Conditions

When an application has multiple possible states, you can use an if/else if/else structure to select the correct UI.

Example:

function App() {
  const score = 75;
  let result;
  if (score >= 90) {
    result = "Excellent";
  } else if (score >= 60) {
    result = "Passed";
  } else {
    result = "Failed";
  }
  return <h2>Result: {result}</h2>;
}
export default App;

Output: Result: Passed

Explanation: The first condition is false, but the second condition is true. Therefore, the component displays Passed.

Example with User Roles

function App() {
  const role = "editor";
  let dashboard;
  if (role === "admin") {
    dashboard = <h2>Admin Dashboard</h2>;
  } else if (role === "editor") {
    dashboard = <h2>Editor Dashboard</h2>;
  } else {
    dashboard = <h2>User Dashboard</h2>;
  }
  return <div>{dashboard}</div>;
}
export default App;

Output: Editor Dashboard


11. Conditional Rendering with React State

Conditional Rendering is often combined with the useState Hook. State allows the UI to change in response to user interactions, such as clicking a button to show or hide content.

Example: Show and Hide Message

import { useState } from "react";
function App() {
  const [showMessage, setShowMessage] = useState(false);
  function handleToggle() {
    setShowMessage((currentValue) => !currentValue);
  }
  return (
    <div>
      <button onClick={handleToggle}>
        {showMessage ? "Hide Message" : "Show Message"}
      </button>
      {showMessage && <p>Welcome to React JS!</p>}
    </div>
  );
}
export default App;

Explanation: The initial state is false, so the message is hidden. Clicking the button toggles the state, causing React to display or hide the paragraph and update the button label.


12. Conditional Rendering Based on Props

Props allow a parent component to pass information to a child component. A child component can use a Boolean or another prop value to decide which content to display.

Example:

function UserStatus({ isOnline }) {
  return (
    <p>
      {isOnline ? "User is Online" : "User is Offline"}
    </p>
  );
}
function App() {
  return (
    <div>
      <UserStatus isOnline={true} />
      <UserStatus isOnline={false} />
    </div>
  );
}
export default App;

Explanation: The first component receives true and displays Online. The second receives false and displays Offline.


13. Conditional Rendering for Login and Logout

Authentication interfaces commonly display different buttons depending on whether the user is logged in.

Example:

import { useState } from "react";
function App() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  return (
    <div>
      <h2>User Account</h2>
      {isLoggedIn ? (
        <div>
          <p>Welcome back!</p>
          <button onClick={() => setIsLoggedIn(false)}>
            Logout
          </button>
        </div>
      ) : (
        <div>
          <p>Please log in to continue.</p>
          <button onClick={() => setIsLoggedIn(true)}>
            Login
          </button>
        </div>
      )}
    </div>
  );
}
export default App;

Explanation: The Login button sets the state to true, so the logged-in UI appears. The Logout button sets the state to false, returning to the login UI.

Security note: Hiding a component based on a role or login state only controls the visible UI. Real authentication and authorization must also be enforced by the server or backend.


14. Conditional Rendering for Loading and Error States

Applications often need to show a loading message while data is being retrieved and an error message if the operation fails.

Example:

function DataStatus({ isLoading, hasError, data }) {
  if (isLoading) {
    return <p>Loading data...</p>;
  }
  if (hasError) {
    return <p>Something went wrong. Please try again.</p>;
  }
  if (!data || data.length === 0) {
    return <p>No data available.</p>;
  }
  return (
    <ul>
      {data.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}
export default DataStatus;

Explanation: The component checks the loading state first, then the error state, then whether data is empty. If none of those conditions applies, it displays the list of data items.


15. Conditional Rendering in Lists

Conditional Rendering can be combined with the map() method to display different content for each item in a list.

Example:

function App() {
  const tasks = [
    { id: 1, name: "Learn HTML", completed: true },
    { id: 2, name: "Learn CSS", completed: false },
    { id: 3, name: "Learn React", completed: true }
  ];
  return (
    <div>
      <h2>Task List</h2>
      <ul>
        {tasks.map((task) => (
          <li key={task.id}>
            {task.name} {task.completed ? "✓ Completed" : "Pending"}
          </li>
        ))}
      </ul>
    </div>
  );
}
export default App;

Explanation: Each task displays a different status based on its completed property. The unique key helps React identify each list item.


16. Conditional Rendering for Form Validation

Conditional Rendering can display validation feedback when a form field is empty or invalid.

Example:

import { useState } from "react";
function App() {
  const [email, setEmail] = useState("");
  const [submitted, setSubmitted] = useState(false);
  const isEmailMissing = email.trim() === "";
  function handleSubmit(event) {
    event.preventDefault();
    setSubmitted(true);
  }
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="email">Email:</label>
      <input
        id="email"
        type="email"
        value={email}
        onChange={(event) => setEmail(event.target.value)}
      />
      {submitted && isEmailMissing && (
        <p>Email is required.</p>
      )}
      {submitted && !isEmailMissing && (
        <p>Form submitted.</p>
      )}
      <button type="submit">Submit</button>
    </form>
  );
}
export default App;

Explanation: The error message appears after the user submits the form and the email field is empty. If the field contains a non-empty value, a confirmation message appears. In a production form, validate the email format and any other requirements before confirming success.


17. Conditional Rendering of CSS Classes

Conditions can also be used to assign different CSS classes. This allows an element's appearance to change according to application state.

Example:

function App() {
  const isActive = true;
  return (
    <button className={isActive ? "active-button" : "inactive-button"}>
      Status
    </button>
  );
}
export default App;

Explanation: When isActive is true, the button receives the active-button class. Otherwise, it receives the inactive-button class.

Define the corresponding CSS classes in your stylesheet to control their appearance.


18. Conditional Rendering of Components

React allows you to render an entire component conditionally. This is useful when different application states require different sections of the interface.

Example:

function AdminPanel() {
  return <h2>Admin Panel</h2>;
}
function UserPanel() {
  return <h2>User Panel</h2>;
}
function App() {
  const isAdmin = true;
  return (
    <div>
      {isAdmin ? <AdminPanel /> : <UserPanel />}
    </div>
  );
}
export default App;

Explanation: If isAdmin is true, React renders AdminPanel. Otherwise, it renders UserPanel.


19. Difference Between Conditional Rendering Methods

Method Syntax Best Use
if statement if (condition) return ... Complex logic or early returns
if/else if (...) ... else ... Choosing between multiple outcomes
Ternary operator condition ? A : B Choosing one of two outputs inside JSX
Logical AND condition && A Showing content only when a condition is true
Logical OR value || fallback Providing fallback values for falsy data
null return null Rendering nothing from a component
JSX variable let content = ... Organizing more involved rendering logic

20. Common Mistakes in Conditional Rendering

Mistake 1: Using if Directly Inside JSX

// Incorrect
return (
  <div>
    if (isLoggedIn) {
      <p>Welcome</p>
    }
  </div>
);

Correction: Use an expression or calculate the content before returning JSX.

return (
  <div>
    {isLoggedIn ? <p>Welcome</p> : <p>Please log in</p>}
  </div>
);

Mistake 2: Forgetting the Else Branch

Use a ternary expression when both conditions require different content. If you only need to show something when the condition is true, the && operator may be more appropriate.

Mistake 3: Rendering Zero Accidentally

// Can display 0 when messageCount is zero
{messageCount && <p>New messages</p>}
// Better
{messageCount > 0 && <p>New messages</p>}

Mistake 4: Using Too Many Nested Ternary Operators

Deeply nested ternaries can make code difficult to read. Use an if/else if structure or separate components when the logic becomes complex.

Mistake 5: Confusing Assignment and Comparison

// Use comparison when checking a value
role === "admin"

Use comparison operators such as === when checking whether two values are equal. Do not accidentally use assignment when writing a condition.


21. Best Practices for Conditional Rendering

  • Choose the rendering method that makes the condition easiest to understand.
  • Use the ternary operator for simple two-way decisions.
  • Use && when content should appear only when a Boolean condition is true.
  • Use explicit comparisons such as count > 0 to avoid accidentally rendering zero.
  • Use early returns for loading, error, or other special component states.
  • Keep complex conditions in clearly named variables or functions.
  • Extract repeated or complicated UI into reusable components.
  • Use unique keys when conditionally rendering lists.
  • Test both true and false conditions.
  • Remember that hiding UI is not a replacement for backend security checks.

22. Practical Project: Conditional Rendering Dashboard

Objective: Create a small dashboard with a login toggle, a notification message, and different content based on the user's login state.

Complete Code:

import { useState } from "react";
function App() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [showNotification, setShowNotification] = useState(false);
  return (
    <div>
      <h1>React Dashboard</h1>
      {isLoggedIn ? (
        <div>
          <h2>Welcome to your dashboard!</h2>
          <button onClick={() => setIsLoggedIn(false)}>
            Logout
          </button>
          <button onClick={() => setShowNotification((value) => !value)}>
            {showNotification ? "Hide Notification" : "Show Notification"}
          </button>
          {showNotification && (
            <p>You have a new notification.</p>
          )}
        </div>
      ) : (
        <div>
          <p>Please log in to access the dashboard.</p>
          <button onClick={() => setIsLoggedIn(true)}>
            Login
          </button>
        </div>
      )}
    </div>
  );
}
export default App;

Project Explanation

  1. The isLoggedIn state determines whether the login prompt or dashboard is displayed.
  2. The Login button changes isLoggedIn to true.
  3. The Logout button changes isLoggedIn to false.
  4. The showNotification state determines whether the notification appears.
  5. The ternary operator chooses the logged-in or logged-out interface.
  6. The logical AND operator displays the notification only when the notification state is true.

23. Interview Questions and Answers

Q1. What is Conditional Rendering in React?

Answer: Conditional Rendering means displaying different JSX elements or components depending on a condition.

Q2. Which JavaScript techniques can be used for Conditional Rendering?

Answer: Common techniques include if statements, ternary operators, logical AND, logical OR, variables, and returning null.

Q3. What is the ternary operator?

Answer: It is a conditional expression written as condition ? valueIfTrue : valueIfFalse.

Q4. When should we use the logical AND operator?

Answer: Use && when an element should be rendered only if a condition is true.

Q5. What does returning null mean in React?

Answer: It means the component renders no visible content for that render.

Q6. Can props be used for Conditional Rendering?

Answer: Yes. A component can check prop values and display different content accordingly.

Q7. Can state control Conditional Rendering?

Answer: Yes. When state changes, React renders the UI based on the new state value.

Q8. What is a common mistake with logical AND?

Answer: Using a number such as zero directly as the left-hand condition can cause React to display 0. Use an explicit Boolean condition such as count > 0.

Q9. Can we render different components based on a condition?

Answer: Yes. A condition can select between components, such as an admin panel and a user panel.

Q10. Why is Conditional Rendering useful?

Answer: It helps create dynamic interfaces for authentication, forms, notifications, data loading, errors, and user-specific content.


24. Practice Exercises

  1. Create a component that displays Welcome when a user is logged in and Login Required otherwise.
  2. Use the ternary operator to show Pass or Fail based on a student's marks.
  3. Use the logical AND operator to display a notification only when the notification count is greater than zero.
  4. Create a Show/Hide button using useState.
  5. Display a loading message while a Boolean loading state is true.
  6. Display an error message when a form field is empty after submission.
  7. Render an Admin Dashboard or User Dashboard based on a role prop.
  8. Create a list of tasks and conditionally display Completed or Pending for each task.

25. Quick Revision Checklist

  • Understand the meaning and purpose of Conditional Rendering.
  • Know how to use if and if/else statements.
  • Understand the ternary operator.
  • Know how to use the logical AND operator safely.
  • Understand fallback values using logical OR.
  • Know how to return null when no content should appear.
  • Understand Conditional Rendering with state and props.
  • Know how to display loading, error, and empty states.
  • Understand how to render different components based on conditions.
  • Follow readability, accessibility, and security best practices.

26. Useful Learning Resources


Conclusion

Conditional Rendering allows React applications to display the correct content according to conditions, props, state, and user interactions. The main techniques include if statements, ternary operators, logical AND, logical OR, variables, and returning null. Understanding when to use each technique helps developers build clear, dynamic, and maintainable React applications.

To learn more, explore the JustAcademy React JS Training Course and register for a course demo.

whatsapp